<?php


namespace app\api\controller;


use app\admin\model\CourseEnroll;
use app\admin\model\CourseOrder;
use app\admin\model\ExperCourse;
use app\admin\model\UserWithdrawals;
use app\common\controller\Api;
use app\common\model\Agreement;
use app\common\model\CarersApply;
use app\common\model\City;
use app\common\model\Course;
use app\common\model\MoneyLog;
use app\common\model\Service;
use app\common\model\service\Order;
use app\common\model\Withdrawals;
use fast\Http;
use GuzzleHttp\Client;
use app\common\model\User;
use app\api\validate\Carers as CarersValidate;
use think\Db;
use think\Exception;
use think\Log;
use think\Model;
use think\Response;

class Carers extends Api
{
    protected $noNeedLogin = ['mnpLogin', 'getSmsCode', 'smsLogin', 'detail', 'courseNotify', 'courseReturn', 'richText'];
    protected $noNeedRight = '*';

//    protected $app_id = 'wx9290cdf0e8a69b12';
//    protected $app_secret = '730a2c7939b086f2b6cd43e9c1f91980';

    protected $app_id = 'wx31b06000c8edf2cd';
    protected $app_secret = '3aadd50c541276488db9d1626885f1e2';


    public function testLogin()
    {
        $this->auth->direct(5);
        $user = $this->auth->getUserinfo();
        $this->success('获取成功', $user);
    }

    public function mnpLogin()
    {
        
        $post = $this->request->post();
        extract($post);
        if (empty($code) ||  empty($phone_code)) {
            $this->error('缺少必要参数!');
        }
        try {
            //获取授权信息
            $result = $this->getOpenid($code);
            if (!isset($result['session_key']) || !isset($result['openid'])) {
                $this->error('登录异常');
            }
            $token = $this->getAccessToken($phone_code);
            if (isset($token['errcode'])) {
                $this->error($token['errmsg']);
            }
            $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" . $token['access_token'];
            $client = new Client();
            $response = json_decode($client->post($url, [
                'json' => [
                    'code' => $phone_code
                ]
            ])->getBody(), true);
            if ($response['errcode'] == 0) {
                $phone = $response['phone_info'];

                $user = User::get([
                    'carers_openid' => $result['openid']
                ]);
                Log::record(1, 'log');
                if (!empty($user)) {

                    Log::record(2, 'log');
                    $this->auth->direct($user['id']);
                } else {

                    Log::record(3, 'log');
                    $user = User::get([
                        'mobile'   => $phone['phoneNumber']
                    ]);
                    if ($user) {
                        Log::record(4, 'log');
                        // 更新个人数据
                        $result = $this->auth->updateRegister($result['openid'], $phone['phoneNumber'], 1);
                    } else {
                        // 写入个人数据

                        Log::record(5, 'log');
                        $invite_code = isset($invite_code) ? $invite_code : 0;
                        $result = $this->auth->oauthRegister($result['openid'], $phone['phoneNumber'], $token['access_token'], $invite_code, 1);
                    }
                }
                $user = $this->auth->getUserinfo();
                $user['avatar'] = get_file_url($user['avatar']);
                if (!$user['level']) {
                    //是否存在申请
                    if ($apply = CarersApply::where('user_id', $user['id'])->find()) {
                        if ($apply['status'] == 0) {
                            $user['apply']['url'] = 'tip_page';
                            $user['apply'] = [
                                'url' => 'success_page',
                                'msg' => '您的申请已提交至平台，稍后会有专人与您联系，请您随时留意'
                            ];
                        } elseif ($apply['status'] == 2) {
                            $user['apply'] = [
                                'url' => 'fail_page',
                                'msg' => $apply['reason']
                            ];
                        }
                    } else {
                        $user['apply']['url'] = 'apply_page';
                    }
                }

                Log::record($user, 'log');
                $this->success('获取成功', $user);
            } else {
                $this->error($response['errmsg']);
            }

            $this->success('获取成功', $result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 获取access_token
     */
    public function getAccessToken()
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->app_id . '&secret=' . $this->app_secret;
        $result = json_decode(Http::get($url), true);
        return $result;
    }

    /**
     * @param $code 用来交换获取openid 跟 session_key
     */
    public function getOpenid($code)
    {
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->app_id . '&secret=' . $this->app_secret . '&js_code=' . $code . '&grant_type=authorization_code';

        $result = Http::get($url);

        $wxResult = json_decode($result, true);
        if (empty($wxResult)) {
            $this->error('获取sessin_key及openID时异常');
        }

        if (isset($wxResult['errcode']) && $wxResult['errcode'] != 0) {
            $this->error($wxResult['errmsg']);
        }

        $data = [
            'openid' => $wxResult['openid'],
            'session_key' => $wxResult['session_key']
        ];

        return $data;
    }

    /**
     * 获取手机号验证码
     */
    public function getSmsCode()
    {

    }

    /**
     * 手机验证码登录
     */
    public function smsLogin()
    {

    }

    /**
     * 用户端陪诊师详情
     */
    public function detail()
    {
        $id = $this->request->get('id');
        if (empty($id)) {
            $this->error('缺少必要参数!');
        }
        if (!$user = User::where('level', 1)->find($id)) {
            $this->error('陪诊师信息不存在');
        }

        //常驻医院
        $hospital = ''; $project = '';
        if (!empty($user['service_hospital'])) {
            $list =  \app\common\model\Hospital::whereIn('id', explode(',', $user['service_hospital']))->column('title');
            $hospital = implode(',', $list);
        }
        //陪诊项目
        if (!empty($user['service_hospital'])) {
            $list =  Service::whereIn('id', explode(',', $user['service_project']))->column('title');
            $project = implode(',', $list);
        }

        $data = [
            'avatar' => $user['avatar'],
            'realname' => $user['realname'],
            'gender' => $user['gender'] ? '男' : '女',
            'age' => $user['age'],
            'group_name' => $user['group_name'],
            'nurse_age' => $user['nurse_age'].'年',
            'carers_num' => Order::where(['status' => 4, 'escort_id' => $user['id']])->count(),
            'comment_ratio' => $user['comment_ratio'],
            'hospital' => $hospital,
            'project' => $project,
            'intro' => $user['intro'],
            'city' => City::get($user['city_id'])['city']
        ];

        $this->success('获取成功', $data);
    }

    /**
     * 城市列表
     */
    public function city()
    {
        $data = City::select();
        $this->success('获取成功', $data);
    }
    
    /**
     * 申请成为陪诊师
     */
    public function apply()
    {
        $data = $this->request->post();
        $data['user_id'] = $this->auth->id;

        $validate = validate(CarersValidate::class);
        if (!$validate->scene('apply')->check($data)) {
            $this->error($validate->getError());
        }

        Db::startTrans();
        try {
            if ($carersApply = CarersApply::where('user_id', $data['user_id'])->find()) {
                $data['status'] = 0;
                $carersApply->allowField(true)->save($data);
            } else {
                $carersApply = new CarersApply($data);
                $carersApply->allowField(true)->save();
            }

            Db::commit();
            $this->success('申请已提交，等待审核');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 陪诊师信息
     */
    public function info()
    {
        $user = User::get($this->auth->id);

        $data = [
            'id' => $user['id'],
            'avatar' => $user['avatar'],
            'gender' => $user['gender'] ? '男' : '女',
            'age' => $user['age'],
            'group_name' => $user['group_name'],
            'proportion' => $user['proportion'],
            'money' => $user['money'],
            'realname' => $user['realname'],
            'idcard_name' => $user['idcard_name'],
            'idcard_sn' => $user['idcard_sn'],
            'auth_certificate' => $user['auth_certificate'],
            'current_status' => $user['current_status'],
            'level' => $user['level']
        ];
        if (!$user['level']) {
            //是否存在申请
            if ($apply = CarersApply::where('user_id', $user['id'])->find()) {
                if ($apply['status'] == 0) {
                    $data['apply']['url'] = 'tip_page';
                    $data['apply'] = [
                        'url' => 'success_page',
                        'msg' => '您的申请已提交至平台，稍后会有专人与您联系，请您随时留意'
                    ];
                } elseif ($apply['status'] == 2) {
                    $data['apply'] = [
                        'url' => 'fail_page',
                        'msg' => $apply['reason']
                    ];
                }
            } else {
                $data['apply']['url'] = 'apply_page';
            }
        }

        $this->success('获取成功', $data);
    }

    /**
     * 实名认证
     */
    public function auth()
    {
        $data = $this->request->post();

        $validate = validate(CarersValidate::class);
        if (!$validate->scene('auth')->check($data)) {
            $this->error($validate->getError());
        }

        Db::startTrans();
        try {
            Db::name('user')->where('id', $this->auth->id)->update([
                'auth_certificate' => 1,
                'idcard_name' => $data['realname'],
                'idcard_sn' => $data['idcard'],
                'age' => get_age($data['idcard']),
                'gender' => get_sex($data['idcard']),
                'birthday' => get_birthday($data['idcard'])
            ]);
            Db::commit();
            $this->success('认证成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 设置当前状态
     */
    public function currentStatus()
    {
        $status = $this->request->get('status', 0);

        $user = $this->auth->getUser();
        $user->current_status = $status;
        $user->save();

        $this->success('操作成功');
    }

    /**
     * 提现
     */
    public function withdrawals()
    {
        $data = $this->request->post();
        $data['user_id'] = $this->auth->id;

        $validate = validate(CarersValidate::class);
        if (!$validate->scene('withdrawals')->check($data)) {
            $this->error($validate->getError());
        }

        Db::startTrans();
        try {
            $bank = \app\common\model\Bank::get($data['bank_id']);

            //提现手续费比例
            $withdrawals_rate = config('site.withdrawals_rate');
            $receipt_money = number_format($data['money'] - $data['money']*$withdrawals_rate/100, 2);

            //创建提现订单
            $withdrawasl = Withdrawals::create([
                'user_id' => $data['user_id'],
                'money' => $data['money'],
                'fee' => number_format($data['money']*$withdrawals_rate/100, 2),
                'receipt_money' => $receipt_money,
                'type' => 0,
                'holder' => $bank['holder'],
                'bank' => $bank['bank'],
                'subbranch' => $bank['subbranch'],
                'account' => $bank['account'],
                'state' => 0
            ]);

            //生成资金日志
            MoneyLog::income($data['user_id'], $data['money'], 1, 201, $withdrawasl['id']);

            Db::commit();
            $this->success('申请已提交，等待后台审核');
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 提现手续费
     */
    public function calcFee()
    {
        $withdrawals_rate = config('site.withdrawals_rate');
        $money = $this->request->get('money', 0);
        $data = bcdiv($money*$withdrawals_rate, 100, 2);
        $this->success('计算成功', $data);
    }

    /**
     * 余额明细
     */
    public function moneyLog()
    {
        $page = $this->request->get('page', 1);
        $size = $this->request->get('size', 10);
        $time = $this->request->get('time', date('Y-m-d', time()));

        $where = [];
        $where['user_id'] = ['=', $this->auth->id];
        $where['createtime'] = ['between time', [strtotime($time),(strtotime($time) + 86399)]];
        $count = Db::name('user_money_log')
            ->where($where)
            ->count();

        $list = Db::name('user_money_log')
            ->where($where)
            ->field('id,user_id,type,money,memo,FROM_UNIXTIME(createtime, "%Y-%m-%d %H:%i:%s") as createtime')
            ->order('id desc')
            ->page($page, $size)
            ->select();

        $data = [
            'page' => $page,
            'size' => $size,
            'count' => $count,
            'list' => $list
        ];

        $this->success('获取成功', $data);
    }

    /**
     * 提现记录
     */
    public function withdrawalsLog()
    {
        $page = $this->request->get('page', 1);
        $size = $this->request->get('size', 10);

        $count = UserWithdrawals::where(['user_id' => $this->auth->id])->count();

        $list = UserWithdrawals::where(['user_id' => $this->auth->id])
            ->order('id desc')
            ->page($page, $size)
            ->select();

        $data = [
            'page' => $page,
            'size' => $size,
            'count' => $count,
            'list' => $list
        ];

        $this->success('获取成功', $data);
    }

    /**
     * 邀请陪诊师
     */
    public function invite()
    {
        $user = $this->auth->getUser();

        if (empty($user['carers_qr_image'])) {
            $token = $this->getAccessToken()['access_token'];
            $url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$token";
            $data = json_encode([
                'path' => 'pages/login/login?user_id=' . $user->id,
            ]);
            $http = new Http;
            $response = $http->post($url, $data);
            $res = json_decode($response, true);
            $file = self::saveTempImageByContent($response);
            $user->carers_qr_image = $file;
            $user->save();
        }

//        $url = $this->request->domain().'/share?user_id='.$user['id'];
        $data = [
            'share_image' => get_file_url(config('site.share_image')),
            'avatar' => $user['avatar'],
            'nickname' => $user['realname'],
            'qrcode' => $this->request->domain().'/'.$user['carers_qr_image'],
            'invite_code' => $user['id']
        ];
        $this->success('获取成功', $data);
    }

    static function saveTempImageByContent($content)
    {
        $dir1 = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($dir1)) @mkdir($dir1, 0700);
        $save_name = md5(base64_encode($content)) . '.jpg';
        $save_path = 'uploads/qrcode/' . $save_name;
        $fp = fopen($dir1 . $save_name, 'w');
        fwrite($fp, $content);
        fclose($fp);
        return $save_path;
    }

    /**
     * 创建专属二维码
     */
    public function build($text)
    {
        $config = get_addon_config('qrcode');
        $params = $this->request->get();
        $params = array_intersect_key($params, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));
        $params['size'] = 200;
        $params['text'] = $text;
        $params['label'] = '';
        $params['errorcorrection'] = 'low';
        $qrCode = \addons\qrcode\library\Service::qrcode($params);
        $mimetype = $config['format'] == 'png' ? 'image/png' : 'image/svg+xml';
        $response = Response::create()->header("Content-Type", $mimetype);
        // 写入到文件
        if ($config['writefile']) {
            $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath);
            }
            if (is_really_writable($qrcodePath)) {
                $filePath = $qrcodePath . md5(implode('', $params)) . '.' . $config['format'];
                $qrCode->writeFile($filePath);
                $code_name = md5(implode('', $params)) . '.' . $config['format'];
            }
        }
        return '/uploads/qrcode/'.$code_name;
    }

    /**
     * 已选医院
     */
    public function hospital()
    {
        $service_hospital = $this->auth->getUser()['service_hospital'];
        $list = [];
        if (!empty($service_hospital)) {
            $hospital_ids = explode(',', $service_hospital);
            $list = \app\common\model\Hospital::whereIn('id', $hospital_ids)->select();
        }
        $this->success('获取成功', $list);
    }

    /**
     * 删除已选医院
     */
    public function delHospital()
    {
        $id = $this->request->post('id');
        $hospital_arr = explode(',', $this->auth->getUser()['service_hospital']);
        $key=array_search($id,$hospital_arr,true);
        unset($hospital_arr[$key]);
        $service_hospital = '';
        if (count($hospital_arr)) $service_hospital = implode(',', $hospital_arr);
        $user = $this->auth->getUser();
        $user->service_hospital = $service_hospital;
        $user->save();

        $this->success('操作成功');
    }

    /**
     * 当前城市医院列表
     */
    public function cityHospital()
    {
        $list = \app\common\model\Hospital::where('city_id', $this->auth->getUser()['city_id'])->select();

        $service_hospital = $this->auth->getUser()['service_hospital'];
        foreach ($list as &$item) {
            $item['is_selected'] = 0;
            if (!empty($service_hospital) && in_array($item['id'], explode(',', $service_hospital))) {
                $item['is_selected'] = 1;
            }
        }
        $this->success('获取成功', $list);
    }

    /**
     * 选择医院
     */
    public function selectHospital()
    {
        $data = $this->request->post();
        $service_hospital = '';
        if (!empty($data['ids'])) {
            $service_hospital = implode(',', $data['ids']);
        }
        $user = $this->auth->getUser();
        $user->service_hospital = $service_hospital;
        $user->save();
        $this->success('保存成功');
    }

    /**
     * 已选服务项目
     */
    public function project()
    {
        $service_project = $this->auth->getUser()['service_project'];
        $list = [];
        if (!empty($service_project)) {
            $project_ids = explode(',', $service_project);
            $list = Service::whereIn('id', $project_ids)->select();
        }
        $this->success('获取成功', $list);
    }

    /**
     * 删除已选服务项目
     */
    public function delProject()
    {
        $id = $this->request->post('id');
        $project_arr = explode(',', $this->auth->getUser()['service_project']);
        $key=array_search($id,$project_arr,true);
        unset($project_arr[$key]);
        $service_project = '';
        if (count($project_arr)) $service_project = implode(',', $project_arr);
        $user = $this->auth->getUser();
        $user->service_project = $service_project;
        $user->save();

        $this->success('操作成功');
    }

    /**
     * 服务项目列表
     */
    public function service()
    {
        $list = Service::select();
        $service_project = $this->auth->getUser()['service_project'];
        foreach ($list as &$item) {
            $item['is_selected'] = 0;
            if (!empty($service_project) && in_array($item['id'], explode(',', $service_project))) {
                $item['is_selected'] = 1;
            }
        }
        $this->success('获取成功', $list);
    }

    /**
     * 选择项目
     */
    public function selectProject()
    {
        $data = $this->request->post();
        $service_project = '';
        if (!empty($data['ids'])) {
            $service_project = implode(',', $data['ids']);
        }
        $user = $this->auth->getUser();
        $user->service_project = $service_project;
        $user->save();
        $this->success('保存成功');
    }

    /**
     * 平台客服
     */
    public function customerService()
    {
        $data = [
            'qrcode' => get_file_url(config('site.escort_ewm')),
            'phone' => config('site.escort_phone')
        ];
        $this->success('获取成功', $data);
    }

    /**
     * 富文本统一
     */
    public function richText()
    {
        $data = Agreement::get($this->request->get('id', 3))['content'];
        $this->success('获取成功', $data);
    }

    /**
     * 教学视频列表
     */
    public function course()
    {
        $page = $this->request->get('page', 1);
        $size = $this->request->get('size', 10);

        $count = Course::count();
        $list = Course::field('id,image,title,price,intro')->select();
        foreach ($list as &$item) {
            $item['image'] = get_file_url($item['image']);
        }

        $data = [
            'page' => $page,
            'size' => $size,
            'count' => $count,
            'list' => $list
        ];

        $this->success('获取成功', $data);
    }

    /**
     * 课程详情
     */
    public function courseDetail()
    {
        $id = $this->request->get('id', 0);
        if (!$course = Course::get($id)) {
            $this->error('课程不存在');
        }
        $course['images'] = explode(',', $course['images']);
        $course['attachfile'] = get_file_url($course['attachfile']);
        $course['image'] = get_file_url($course['image']);
        foreach ($course['images'] as $value) {
            $val[] = get_file_url($value);
        }
        $course['images'] = $val;

        $this->success('获取成功', $course);
    }

    /**
     * 购买教学课程视频
     */
    public function buyCourse()
    {
        $data = $this->request->post();
        $data['user_id'] = $this->auth->id;

        $validate = validate(CarersValidate::class);
        if (!$validate->scene('buy_course')->check($data)) {
            $this->error($validate->getError());
        }

        Db::startTrans();
        try {
            $course = Course::get($data['course_id']);
            $user = User::get($this->auth->id);
            $map = [
                'order_sn' => create_order_sn('course_order', 'order_sn', '', 4),
                'user_id' => $user['id'],
                'course_id' => $course['id'],
                'course_name' => $course['title'],
                'money' => $course['price'],
                'pay_status' => 0,
                'create_time' => time()
            ];
            $order = CourseOrder::create($map);

            //发起支付
            $param = [
                'amount' => $order->money,
                'orderid' => $order->order_sn,
                'type' => 'wechat',
                'title' => '购买'.$course->title,
                'notifyurl' => $this->request->domain().'/api/carers/courseNotify/paytype/wechat',
                'returnurl' => $this->request->domain().'/api/carers/courseReturn/paytype/wechat/out_trade_no/' . $order->order_sn,
                'method' => "miniapp",
                'openid' => $user->carers_openid,
            ];
            $result = \addons\epay\library\Service::submitOrder($param);
            Db::commit();
            $this->success('订单提交成功', $result);
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 教学课程支付回调
     */
    public function courseNotify()
    {
        $paytype = $this->request->param('paytype');
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            Log::record('签名错误', 'error');
            return;
        }
        $data = $pay->verify();
        Log::record($data, 'error');
        try {
            $out_trade_no = $data['out_trade_no'];
            if (!$order = CourseOrder::where('order_sn', $out_trade_no)->find()) {
                echo '订单不存在';
                return;
            }
            //修改订单状态
            $order->pay_status = 1;
            $order->pay_time = time();
            $order->transaction_id = $data['transaction_id'];
            $order->save();
        } catch (Exception $e) {
            Log::record($e->getMessage(), 'error');
        }
        //下面这句必须要执行,且在此之前不能有任何输出
        return $pay->success()->send();
    }

    /**
     * 支付返回，仅供开发测试
     */
    public function courseReturn()
    {
        $paytype = $this->request->param('paytype');
        $out_trade_no = $this->request->param('out_trade_no');
        $pay = \addons\epay\library\Service::checkReturn($paytype);
        if (!$pay) {
            $this->error('签名错误', '');
        }

        $this->success("请返回网站查看支付结果", addon_url("epay/index/index"));
    }

    /**
     * 已购教学课程
     */
    public function courseList()
    {
        $page = $this->request->get('page', 1);
        $size = $this->request->get('size', 10);

        $count = CourseOrder::alias('o')
            ->join('course c', 'c.id = o.course_id', 'left')
            ->where(['user_id' => $this->auth->id, 'pay_status' => 1])
            ->count();
        $list = CourseOrder::alias('o')
            ->join('course c', 'c.id = o.course_id', 'left')
            ->where(['user_id' => $this->auth->id, 'pay_status' => 1])
            ->field('o.id,c.image,o.money,c.title,c.intro,o.create_time,c.attachfile')
            ->page($page, $size)
            ->select();
        foreach ($list as &$item) {
            $item['image'] = get_file_url($item['image']);
            $item['attachfile'] = get_file_url($item['attachfile']);
            $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
        }

        $data = [
            'page' => $page,
            'size' => $size,
            'count' => $count,
            'list' => $list
        ];

        $this->success('获取成功', $data);
    }

    /**
     * 体验课程列表
     */
    public function experCourse()
    {
        $page = $this->request->get('page', 1);
        $size = $this->request->get('size', 10);

        $count = ExperCourse::count();
        $list = ExperCourse::field('id,image,title,intro')->select();
        foreach ($list as &$item) {
            $item['image'] = get_file_url($item['image']);
        }

        $data = [
            'page' => $page,
            'size' => $size,
            'count' => $count,
            'list' => $list
        ];

        $this->success('获取成功', $data);
    }

    /**
     * 体验课程详情
     */
    public function experCourseDetail()
    {
        $id = $this->request->get('id', 0);
        if (!$course = ExperCourse::get($id)) {
            $this->error('课程不存在');
        }
        $course['images'] = explode(',', $course['images']);
        $course['attachfile'] = get_file_url($course['attachfile']);
        $course['image'] = get_file_url($course['image']);
        foreach ($course['images'] as $value) {
            $val[] = get_file_url($value);
        }
        $course['images'] = $val;

        $this->success('获取成功', $course);
    }

    /**
     * 体验课程报名
     */
    public function enrollCourse()
    {
        $data = $this->request->post();
        $data['user_id'] = $this->auth->id;

        $validate = validate(CarersValidate::class);
        if (!$validate->scene('enroll_course')->check($data)) {
            $this->error($validate->getError());
        }

        Db::startTrans();
        try {
            CourseEnroll::create([
                'user_id' => $data['user_id'],
                'course_id' => $data['exper_course_id'],
                'realname' => $data['realname'],
                'mobile' => $data['mobile'],
                'remark' => isset($data['remark']) ?? '',
                'create_time' => time()
            ]);
            Db::commit();
            $this->success('报名成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
}